package com.gzhryc.shared_device.oem.h5.mng.controllers.user;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.DefaultEnum;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.ValidateTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.code.agent.dao.db.Agent;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentLevel;
import com.gzhryc.shared_device.oem.code.agent.services.AgentLevelService;
import com.gzhryc.shared_device.oem.code.agent.services.AgentService;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.models.PlacePhysicalStoreUser;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreUserService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.code.user.dao.db.*;
import com.gzhryc.shared_device.oem.code.user.services.*;
import com.gzhryc.shared_device.oem.code.user.services.dto.UserSearch;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.mng.dto.agent.UserData;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class UserController {

    @Route(value = {"/user/list.html"})
    public String list(HttpServletRequest request) {
        return "/user/list.html";
    }

    @Route(value = "/user/list.data")
    public ListResult<UserData> listData(HttpServletRequest request) {
        ListResult<UserData> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        UserSearch search = WebUtils.getParameter(request, UserSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(UserService.self().countBySearch(search));
        List<User> data = UserService.self().findBySearch(search, pageNo, pageLimit);
        if (data != null && data.size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(new ArrayList<>());
            for (User user : data) {
                UserData item = ClassTools.copy(new UserData(), user);
                result.getBody().getData().add(item);
            }

        }
        return result;
    }

    @Route(value = {"/user/add.html"})
    public String add(HttpServletRequest request) {
        request.setAttribute("sexList", DefaultEnum.Sex.values());
        return "/user/edit.html";
    }

    @Route(value = { "/user/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        User user = WebUtils.getParameter(request,User.class);
        try {
            if(UserService.self().add(user)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = {"/user/info.html"})
    public String info(HttpServletRequest request) {
        Long id = WebUtils.getLong(request, "id");
        User user = UserService.self().getById(id);
        if (user != null) {
            WebUtils.setAttribute(request, user);
            Agent agent = AgentService.self().getByUserId(user.getId());
            if(agent != null){
                AgentLevel agentLevel = AgentLevelService.self().getByNum(agent.getLevel());
                request.setAttribute("levelName",agentLevel.getName());
            }

            UserTransferMoneyQrcode qrcode = UserTransferMoneyQrcodeService.self().getByUserId(user.getId());
            if(qrcode != null){
                String resDomain = PropertyTools.get().getString("resDomain");
                qrcode.setQrcode(WebUtils.setHttpDomain(resDomain,qrcode.getQrcode()));
                request.setAttribute("qrcode",qrcode);
            }
        }
        return "/user/info.html";
    }

    @Route(value = { "/user/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        Long id = WebUtils.getLong(request,"id");
        try {
            if(UserService.self().deleteById(id)){
                result.setCode(DtoConstants.SUCCESS,null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = "/user/wx_user/list.data")
    public ListResult<UserTransferMoneyWX> wxUserListData(HttpServletRequest request) {
        ListResult<UserTransferMoneyWX> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        result.getBody().setData(UserTransferMoneyWXService.self().findByUserId(userId));
        if (result.getBody().getData() != null && result.getBody().getData().size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
        }
        return result;
    }

    @Route(value = "/user/place/list.data")
    public ListResult<PlacePhysicalStore> placeListData(HttpServletRequest request){
        ListResult<PlacePhysicalStore> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        if(userId != null) {
            PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
            search.setUserId(userId);

            result.getBody().setTotal(PlacePhysicalStoreService.self().countJoinBySearch(search));
            List<PlacePhysicalStore> data = PlacePhysicalStoreService.self().findJoinBySearch(search, pageNo, pageLimit);
            if (data != null && data.size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
                result.getBody().setData(data);
            }
        }
        return result;
    }

    @Route(value = "/user/relevance_place/list.data")
    public ListResult<PlacePhysicalStoreUser> relevancePlaceListData(HttpServletRequest request){
        ListResult<PlacePhysicalStoreUser> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long userId = WebUtils.getLong(request,"userId");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(PlacePhysicalStoreUserService.self().countByUserId(userId));
        List<PlacePhysicalStoreUser> data = PlacePhysicalStoreUserService.self().findByUserId(userId,pageNo,pageLimit);
        if (data != null && data.size() > 0) {
            result.setCode(DtoConstants.SUCCESS,null);
            result.getBody().setData(data);
        }
        return result;
    }

    @Route(value = {"/user/pwd/update.html"})
    public String updatePwd(HttpServletRequest request) {
        return "/user/pwd.html";
    }

    @Route(value = { "/user/pwd/update.do" })
    public AjaxResult doUpdatePwd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        Long userId = WebUtils.getLong(request,"userId");
        String newPwd1 = WebUtils.getString(request,"newPwd1");
        String newPwd2 = WebUtils.getString(request,"newPwd2");
        if(StringTools.isNotBlank(newPwd1) && StringTools.isNotBlank(newPwd2)){
            if(newPwd1.equals(newPwd2)) {
                if (ValidateTools.checkPwd(newPwd1)) {
                    try {
                        if (UserService.self().updateLoginPwd(userId, newPwd1)) {
                            result.setCode(DtoConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        result.setMsg(e.getMessage());
                    }
                } else {
                    result.setMsg("密码过于简单，请重新设置");
                }
            }else{
                result.setMsg("确认密码与密码不一致");
            }
        }else{
            result.setMsg("请填写密码");
        }
        return result;
    }

    @Route("/user/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer page = WebUtils.getInteger(request, "page", 1);

        UserSearch search = new UserSearch();
        search.setTrim(term);
        Long total = 0L;
        List<User> list = UserService.self().findBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            for (User user : list) {
                SelectResult.Item item = new SelectResult.Item();
                item.setId(user.getId().toString());
                item.setText(user.getName() + "("+user.getPhone()+")");
                result.getBody().getData().add(item);
            }
            total += list.size();
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }
}
